package main

import (
	"context"
	"flag"
	"fmt"
	"os"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {

	gvr := schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "pods",
	}
	ctx := context.Background()
	kubeconfig := flag.String("kubeconfig", "~/.kube/config", "kubeconfig file")
	flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		fmt.Printf("The kubeconfig cannot be loaded: %v\n", err)
		os.Exit(1)
	}
	client, err := dynamic.NewForConfig(config)
	if err != nil {
		fmt.Printf("NewForConfig err: %v\n", err)
		os.Exit(1)
	}
	un, err := client.Resource(gvr).Namespace("default").Get(ctx, "api-monitor-0", metav1.GetOptions{}, "")
	if err != nil {
		fmt.Printf("client.Resource err: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("%v\n", un)

	name, found, err := unstructured.NestedString(un.Object, "metadata", "name")
	if err != nil || !found {
		fmt.Printf("Cant find name err: %v\n", err)
		os.Exit(1)
	}
	fmt.Println(name)
}
